import CryptoJS from 'crypto-js/crypto-js.js' // crypto-js.js可直接npm install
import JSEncrypt from './jsencrypt.js'  // jsencrypt.js npm install版本是挂载window的，不适配小程序，直接网上下载的适配版的
import login from '@/api/login.js'
import store from '@/store'
import {isObject, isArray} from '@/utils/utils.js'
export default {
    /**
     * RSA加密
     * @param {String} plaintext 
     * @param {String} publickey 
     * (return时对加密串进行特殊字符的转义)
     */
    encryptRSA(plaintext, publickey) {
        let encryptor = new JSEncrypt()
        encryptor.setPublicKey(publickey)
        let ciphertext = encryptor.encrypt(plaintext)
		// return ciphertext
        return encodeURIComponent(ciphertext)
    },
    /**
     * RSA解密
     * @param {String} ciphertext 
     * @param {String} privatekey 
     */
    decryptRSA(ciphertext, privatekey) {
		// ciphertext = decodeURIComponent(ciphertext)
        let decrptor = new JSEncrypt()
        decrptor.setPrivateKey(privatekey)
        let plaintext = decrptor.decrypt(ciphertext)
        return plaintext
    },
    /**
     * AES加密
     * @param {String} key 密钥：十六进制密钥
     * @param {String} plaintext String或者JSON.stringify(obj)
     * @param {String} iv 十六位随机数
     */
    encryptAES(plaintext, key, iv) {
        const srcs = CryptoJS.enc.Utf8.parse(plaintext)
        const lockKey = CryptoJS.enc.Utf8.parse(key)
        const lockIv = CryptoJS.enc.Utf8.parse(iv)
        let cipher = CryptoJS.AES.encrypt(srcs, lockKey, {
            iv: lockIv,
            mode: CryptoJS.mode.CBC,
            padding: CryptoJS.pad.Pkcs7
        })
        return cipher.ciphertext.toString().toUpperCase()
        // return CryptoJS.enc.Base64.stringify(cipher.ciphertext)
    },
    /**
     * AES解密
     * @param {String} key 密钥：十六进制密钥
     * @param {String} ciphertext String
     * @param {String} iv 十六位随机数
     */
    decryptAES(ciphertext, key, iv) {
        const lockKey = CryptoJS.enc.Utf8.parse(key)
        const lockIv = CryptoJS.enc.Utf8.parse(iv)
        // const encrypHexStr = CryptoJS.enc.Hex.parse(ciphertext)
        // const srcs = CryptoJS.enc.Base64.stringify(encrypHexStr)
		
        let plain = CryptoJS.AES.decrypt(ciphertext, lockKey, {
            iv: lockIv,
            mode: CryptoJS.mode.CBC,
            padding: CryptoJS.pad.Pkcs7
        })
        const plained = plain.toString(CryptoJS.enc.Utf8)
        return plained.toString()
    },
    /**
     * SHA-256
     * @param {String} text 编码
     */
    encryptSHA256Encode(text) {
        return CryptoJS.SHA256(encodeURIComponent(text)).toString()
    },
	/**
	 * SHA-256
	 * @param {String} text 不编码
	 */
	encryptSHA256(text) {
	    return CryptoJS.SHA256(text).toString()
	},
    // /**
    //  * MD5
    //  * @param {String} text 
    //  */
    // encryptMD5(text) {
    //     return CryptoJS.MD5(text).toString()
    // },
    // /**
    //  * DES加密
    //  * @param {String} key 密钥：十六进制密钥
    //  * @param {String} plaintext String或者JSON.stringify(obj)
    //  * @param {String} iv 十六位随机数
    //  */
    // encryptDES(plaintext, key, iv) {
    //     const lockKey = CryptoJS.enc.Utf8.parse(key)
    //     const lockIv = CryptoJS.enc.Utf8.parse(iv)
    //     let cipher = CryptoJS.DES.encrypt(plaintext, lockKey, {
    //         iv: lockIv,
    //         mode: CryptoJS.mode.CBC,
    //         padding: CryptoJS.pad.Pkcs7
    //     })
    //     return cipher.ciphertext.toString().toUpperCase()
    // },
    // /**
    //  * DES解密
    //  * @param {String} key 密钥：十六进制密钥
    //  * @param {String} ciphertext String
    //  * @param {String} iv 十六位随机数
    //  */
    // decryptDES(ciphertext, key, iv) {
    //     const lockKey = CryptoJS.enc.Utf8.parse(key)
    //     const lockIv = CryptoJS.enc.Utf8.parse(iv)
    //     let plain = CryptoJS.DES.decrypt(ciphertext, lockKey, {
    //         iv: lockIv,
    //         mode: CryptoJS.mode.CBC,
    //         padding: CryptoJS.pad.Pkcs7
    //     })
    //     const plained = plain.toString(CryptoJS.enc.Utf8)
    //     return plained.toString()
    // },
    /**
     * 生成16位十六进制的数
     * @returns String result  
     */
    randomNumber(number = 16) {
        let result = ''
        for (let i = 0; i < number; i++) {
            result += Math.floor(Math.random() * 16).toString(16)
        }
        return result.toUpperCase()
    },
    /**
     * 对json排序
     * @params {json} params 
     */
    sortParam(params) {
        const sortParam = {}
        Object.keys(params)
            .sort()
            .forEach(key => {
				if (isObject(params[key])) {
					sortParam[key] = this.sortParam(params[key])
				} else if (isArray(params[key])) {
					sortParam[key] = params[key].map(item => {
						if (typeof item !== 'object') {
							return item
						} else if (Array.isArray(item)) {
							return item
						} else {
							return this.sortParam(item)
						}
					})
				} else {
					sortParam[key] = params[key]
				}
            })
        return sortParam
    },
	
	getPublicKey() {
		let reqData = {
		}
		return new Promise(async(resolve, reject) => {
			let [err, res] = await login.getPublicKey(reqData);
            if (res) {
                res = res.data || {};
                uni.setStorageSync('rsaPk', res.key)
				uni.setStorageSync('timeDiff', res.timeDiff)
				resolve(true)
			} else {
				reject(false)
			}
			if (err) {
				reject(false)
			}
		})
		
	},

}